package com.tecode.util;

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidParameterSpecException;
import java.util.Base64;

/**
 * Created by Administrator on 2019/4/18.
 */
public class WXBizDataCrypt {
    private String session_key;
    private String encryptedData;
    private String iv;

    public WXBizDataCrypt() {
    }

    public static String openPassword(String session_key, String encryptedData, String iv) throws Exception{
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] decode_session_key= decoder.decode(session_key);
        byte[] decode_encryptedData = decoder.decode(encryptedData);
        byte[] decode_iv = decoder.decode(iv);


        Provider bc = Security.getProvider("BC");
        if (Security.getProvider("BC") == null) {
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        }

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");
        SecretKeySpec spec = new SecretKeySpec(decode_session_key, "AES");
        AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
        parameters.init(new IvParameterSpec(decode_iv));
        //设置为解密模式
        cipher.init(Cipher.DECRYPT_MODE, spec,parameters);

        byte[] resultByte = cipher.doFinal(decode_encryptedData);

        String result = null;
        if (null != resultByte && resultByte.length > 0) {
            result = new String(resultByte, "UTF-8");
        }

        return result;

    }
}
